import { showToast } from "../../util/util";
import { submitCid as submitCidApi,handleOnline as handleOnlineApi,getPushStatus as getPushStatusApi } from "@/api/push";
import { getCid } from "@/util/push";
const state = {
	online:false,
	ready:false
}
const mutations = {
	SET_ONLINE(state, online) {
		state.online = online;
		uni.$emit('onlineChange',online)
	},
	SET_READY(state, ready) {
		state.ready = ready;
	},
}
const actions = {
	submitCid({
		commit
	}) {
		return new Promise(async (resolve, reject) => {
			try{
				const cid=await getCid();
				await submitCidApi({cid});
				resolve()
			}catch(err){
				console.error('提交CID失败:', err);
				reject(err)
			}
		})
	},
	getPushStatus({commit}){
		return new Promise(async (resolve, reject) => {
			try{
				const result=await getPushStatusApi()
				console.log('获取推送状态成功:', result);
				commit('SET_ONLINE',result.goOnline===1)
				resolve(result)
			}catch(err){
				console.error('获取推送状态失败:', err);
				// 注意这里不重置在线状态，保持当前状态
				reject(err)
			}
		})
	},
	handleOnline({commit},online){
		return new Promise(async (resolve, reject) => {
			try{
				console.log('处理推送状态变更:', online);
				const result = await handleOnlineApi(online);
				commit('SET_ONLINE',online===1)
				resolve(result)
			}catch(err){
				console.error('处理推送状态变更失败:', err);
				showToast('切换播报状态失败，请重试');
				reject(err)
			}
		})
	}
}
export default {
	namespaced: true,
	state,
	mutations,
	actions
}
